package per.liu.ibatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.time.DateTime;

import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * Created by Administrator on 2015/2/11.
 */
public class DateTimeTypeHandler extends BaseTypeHandler<DateTime> {

	@Override public void setNonNullParameter(PreparedStatement ps, int i, DateTime parameter, JdbcType jdbcType) throws SQLException {
		ps.setTimestamp(i, new Timestamp(parameter.getMillis()));
	}

	@Override public DateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
		Timestamp sqlTimestamp = rs.getTimestamp(columnName);
		if (sqlTimestamp != null) {
			return new DateTime(sqlTimestamp.getTime());
		}
		return null;
	}

	@Override public DateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
		if (sqlTimestamp != null) {
			return new DateTime(sqlTimestamp.getTime());
		}
		return null;
	}

	@Override public DateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
		if (sqlTimestamp != null) {
			return new DateTime(sqlTimestamp.getTime());
		}
		return null;
	}
}
